﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace JSExcel
{
    /// <summary>
    /// Upload 的摘要说明
    /// </summary>
    public class Upload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            var rt = new RTData<string>();
            try
            {
                context.Response.ContentType = "application/json;charset=utf-8";
                HttpFileCollection files = HttpContext.Current.Request.Files;
                byte[] b = new byte[files[0].ContentLength];
                Stream fs = files[0].InputStream;
                fs.Read(b, 0, files[0].ContentLength);
                MemoryStream m = new MemoryStream(b);
                string fileName = files[0].FileName.Substring(0, files[0].FileName.LastIndexOf('.')) + DateTime.Now.ToString("yyyyMMddHHmmss") + files[0].FileName.Substring(files[0].FileName.LastIndexOf('.'));
                FileStream f = new FileStream(HttpContext.Current.Server.MapPath("~/upload/" + fileName), FileMode.Create);
                m.WriteTo(f);
                m.Close();
                f.Close();
                f = null;
                m = null;
                rt.Status = RTStatus.Success;
                rt.Message =fileName;
            }
            catch(Exception e) {
                rt.Status = RTStatus.Error;
                rt.Message = e.Message;
            }
            HttpContext.Current.Response.Write(rt.ToString());
            HttpContext.Current.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        public class MessageData {
            public string FileName;
            public MessageData(string fileName) {
                FileName = fileName;
            }
        }
    }
  
}